<template>
  <div class="mill-detail">
    <div class="w">
      <div class="breadcrumb-box clearfix">
        <Breadcrumb class="fl" :breadcrumbs="breadcrumbs" />
      </div>
      <div class="panel-top">
        <div class="item">
          <div class="item-title">
            <div class="name fl">{{$t('dashboard.rate')}}</div>
          </div>
          <div class="item-content">
            <div class="conetnt-item">
              <div class="item-top">
                <spinner v-if="workerFind_init_Loading"/>
                <template v-else>
                  <cu class="value" :val="shares_15m | num" :decimals="2"></cu>
                  <span class="unit">{{shares_unit}}H/S</span>
                </template>
              </div>
              <div class="item-bottom">
                <span class="title">{{$t('mill.shares_15m')}}</span>
              </div>
            </div>
            <div class="conetnt-item">
              <div class="item-top">
                <spinner v-if="workerFind_init_Loading"/>
                <template v-else>
                  <cu class="value" :val="shares_24h | num" :decimals="2"></cu>
                  <span class="unit">{{shares_unit}}H/S</span>
                </template>
              </div>
              <div class="item-bottom">
                <span class="title">{{$t('dashboard.hour_24')}}{{$t('dashboard.rate')}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="item">
          <div class="item-title">
            <div class="name fl">{{$t('dashboard.minging_machine')}}</div>
          </div>
          <div class="item-content">
            <div class="conetnt-item">
              <div class="item-top">
                <spinner v-if="workerFind_init_Loading"/>
                <template v-else>
                  <cu class="value" :val="(reject_rate*100) | num" :decimals="2"></cu>%
                </template>
              </div>
              <div class="item-bottom">
                <span class="title">{{$t('dashboard.refuse_rate')}}</span>
              </div>
            </div>
            <div class="conetnt-item">
              <div class="item-top">
                <spinner v-if="workerFind_init_Loading"/>
                <p v-else class="value text-truncate" :title="worker_name">{{worker_name}}</p>
              </div>
              <div class="item-bottom">
                <span class="title">{{$t('mill.worker_name')}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="item">
          <div class="item-title">
            <div class="name fl">{{$t('mill.request')}}</div>
          </div>
          <div class="item-content">
            <div class="conetnt-item">
              <div class="item-top">
                <spinner v-if="workerFind_init_Loading"/>
                <span v-else class="value">{{share_time}}</span>
              </div>
              <div class="item-bottom">
                <span class="title">{{$t('mill.last_time')}}</span>
              </div>
            </div>
            <div class="conetnt-item">
              <div class="item-top">
                <spinner v-if="workerFind_init_Loading"/>
                <span v-else class="value">{{last_share_ip}}</span>
              </div>
              <div class="item-bottom">
                <span class="title">{{$t('mill.last_ip')}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="panel-bottom">
        <div class="item">
          <div class="item-title">
            <div class="name fl">{{$t('mill.mach_rate')}}</div>
            <div class="button-box fr">
              <button :disabled="workerHistoryLoading || dimension==='1d'" :class="{active:dimension==='1d'}" @click="dimension='1d'">{{$t('unit.day')}}</button>
              <button :disabled="workerHistoryLoading || dimension==='1h'" :class="{active:dimension==='1h'}" @click="dimension='1h'">{{$t('unit.hour')}}</button>
            </div>
          </div>
          <div class="item-content" v-loading="workerHistoryLoading" :element-loading-text="$t('unit.loading')">
            <echarts ref="echarts" :option="echartsOption" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { workerFind, workerHistory } from '@/api';
import { mapGetters } from 'vuex';
import moment from 'moment';
import Breadcrumb from '@/components/Breadcrumb';
import Cu from '@/components/CountUp';
import Echarts from '@/components/Echarts';
import Spinner from '@/components/Spinner';

export default {
  name: 'millDetail',
  components: {
    Breadcrumb,
    Cu,
    Echarts,
    Spinner,
  },
  data() {
    return {
      breadcrumbs: [
        {
          path: '/',
          titleKey: 'router.home',
        },
        {
          path: '/pools/mill',
          titleKey: 'router.mill',
        },
        {
          path: '/mill/',
          titleKey: 'router.noticedetail',
        },
      ],
      worker_id: '',
      node: '',
      shares_15m: 0,
      shares_24h: 0,
      shares_unit: '',
      reject_rate: 0,
      worker_name: '',
      share_time: '',
      last_share_ip: '',
      dimension: '1h',
      count: 24,
      timer: null,
      workerFind_init_Loading: true,
      workerFindLoading: false,
      workerHistoryLoading: false,
      echartsOption: {
        axisPointer: {
          show: true,
          crossStyle: 'dashed',
          snap: true,
          lineStyle: {
            type: 'dashed',
          },
          label: {
            backgroundColor: 'rgba(50,50,50,0.7)',
          },
        },
        tooltip: {
          trigger: 'axis',
        },
        grid: {
          left: 72,
          top: 60,
          right: 72,
          bottom: 60,
        },
        legend: {
          data: [this.$t('home.force'), this.$t('dashboard.refuse_rate')],
          top: '5%',
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [],
          axisLine: {
            lineStyle: {
              color: '#eaeaea',
            },
          },
          nameTextStyle: {
            color: '#333',
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            fontSize: 12,
            color: '#333',
          },
          splitLine: {
            show: false,
          },
        },
        yAxis: [
          {
            type: 'value',
            name: this.$t('home.force'),
            axisLine: {
              show: false,
            },
            nameTextStyle: {
              color: '#333',
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              fontSize: 12,
              color: '#333',
            },
            splitLine: {
              show: false,
            },
          },
          {
            type: 'value',
            name: this.$t('dashboard.refuse_rate'),
            max: 10,
            min: 0,
            interval: 2,
            axisLine: {
              show: false,
            },
            nameTextStyle: {
              color: '#333',
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              fontSize: 12,
              color: '#333',
            },
            splitLine: {
              show: false,
            },
          },
        ],
        series: [
          {
            // 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow'
            data: [],
            type: 'line',
            name: this.$t('home.force'),
            showSymbol: true,
            // symbol:'emptyDiamond',
            symbol: 'emptyDiamond',
            symbolSize: 4,
            showAllSymbol: true,
            itemStyle: {
              normal: {
                color: '#70c1b3',
                borderWidth: 1,
              },
            },
            lineStyle: {
              width: 1,
            },
            smooth: true,
          },
          {
            data: [],
            type: 'line',
            name: this.$t('dashboard.refuse_rate'),
            showSymbol: true,
            symbol: 'emptyDiamond',
            symbolSize: 4,
            showAllSymbol: true,
            itemStyle: {
              normal: {
                color: '#eb547c',
                borderWidth: 1,
              },
            },
            lineStyle: {
              width: 2,
            },
            yAxisIndex: 1,
            smooth: true,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(['subCuid', 'language']),
  },
  created() {
    this.breadcrumbs[2].path = this.$route.path;
    const arr = this.$route.params.id.split('|');
    this.worker_id = arr[0];
    this.node = arr[1];
    this.workerFind();
    this.timer = setInterval(() => {
      this.workerFind();
      this.workerHistory();
    }, 10000);
  },
  destroyed() {
    clearInterval(this.timer);
  },
  methods: {
    toggleEchartsLang() {
      this.echartsOption.legend.data = [this.$t('home.force'), this.$t('dashboard.refuse_rate')];
      this.echartsOption.yAxis[0].name = this.$t('home.force');
      this.echartsOption.yAxis[1].name = this.$t('dashboard.refuse_rate');
      this.echartsOption.series[0].name = this.$t('home.force');
      this.echartsOption.series[1].name = this.$t('dashboard.refuse_rate');
      if (this.$refs.echarts) {
        this.$refs.echarts.setOption(this.echartsOption);
      }
    },
    workerFind() {
      if (this.workerFindLoading) {
        return;
      }
      this.workerFindLoading = true;
      workerFind({
        puid: this.subCuid,
        worker_id: this.worker_id,
        node: this.node,
      })
        .then((res) => {
          if (res.data.status === 1) {
            const data = res.data.data;
            this.shares_15m = data.shares_15m;
            this.shares_24h = data.shares_24h;
            this.shares_unit = data.shares_unit;
            this.reject_rate = (
              Math.floor(data.reject_rate * 10000) / 10000
            ).toFixed(4);
            this.worker_name = data.worker_name;
            this.share_time = data.share_time;
            this.last_share_ip = data.last_share_ip;
          } else {
            this.$message({
              message: this.$t(`api.${res.data.errcode}`),
              type: 'warning',
            });
          }
          this.workerFind_init_Loading = false;
          this.workerFindLoading = false;
        })
        .catch(() => {
          this.$message({
            message: this.$t('error.catchError'),
            type: 'warning',
          });
          this.workerFind_init_Loading = false;
          this.workerFindLoading = false;
        });
    },
    workerHistory() {
      const arr = this.$route.params.id.split('|');
      this.worker_id = arr[0];
      if (!this.worker_id) {
        this.worker_id = arr[0];
      }
      if (!this.node) {
        this.node = arr[1];
      }
      workerHistory({
        puid: this.subCuid,
        worker_id: this.worker_id,
        node: this.node,
        count: this.count,
        dimension: this.dimension,
      }).then((res) => {
        if (res.data.status === 1) {
          const time = [];
          const unit = res.data.unit;
          const shareAccept = [];
          const rejectRate = [];
          res.data.data.reverse().forEach((v) => {
            time.push(v.time);
            shareAccept.push(
              (Math.floor(v.share_accept * 100) / 100).toFixed(2),
            );
            rejectRate.push((v.reject_rate * 100).toFixed(2));
          });
          this.echartsOption.xAxis.data = time;
          this.echartsOption.yAxis[0].name = `${this.$t('dashboard.rate')}(${unit}H/S)`;
          this.echartsOption.yAxis[1].name = `${this.$t('dashboard.refuse_rate')}(%)`;
          this.echartsOption.series[0].data = shareAccept;
          this.echartsOption.series[1].data = rejectRate;
          this.echartsOption.tooltip.formatter = (v) => {
            let str = '';
            v.filter(item => item.axisDim === 'x').forEach((item, index) => {
              if (!index) {
                str += `${this.$t('dashboard.time')}：${moment(item.axisValue * 1000).format(this.dimension === '1h' ? 'YYYY-MM-DD HH:mm' : 'YYYY-MM-DD')}`;
              }
              if (item.color === '#70c1b3') {
                str += `<br/><i style="background:${item.color};display:inline-block;height:12px;width:12px;border-radius:6px;"></i> ${this.$t('dashboard.rate')}：${item.data}(${unit}H/S)`;
              }
              if (item.color === '#eb547c') {
                str += `<br/><i style="background:${item.color};display:inline-block;height:12px;width:12px;border-radius:6px;"></i> ${this.$t('dashboard.refuse_rate')}：${item.data}%`;
              }
            });
            return str;
          };
          this.echartsOption.xAxis.axisLabel.formatter = (value) => {
            const formatterTime = moment(value * 1000).format(
              this.dimension === '1h' ? 'HH:mm YYYY-MM-DD' : 'YYYY-MM-DD',
            );
            return formatterTime.split(' ').join('\n');
          };
          if (this.$refs.echarts) {
            this.$refs.echarts.setOption(this.echartsOption);
          }
        } else {
          this.$message({
            message: this.$t(`api.${res.data.errcode}`),
            type: 'warning',
          });
        }
        this.workerHistoryLoading = false;
      }).catch(() => {
        this.$message({
          message: this.$t('error.catchError'),
          type: 'warning',
        });
        this.workerHistoryLoading = false;
      });
    },
  },
  watch: {
    dimension: {
      handler(val) {
        this.count = val === '1h' ? 24 : 168;
        this.workerHistoryLoading = true;
        this.workerHistory();
      },
      immediate: true,
    },
    subCuid() {
      this.$router.push('/pools/dashboard');
    },
    language() {
      this.toggleEchartsLang();
    },
  },
};
</script>
<style lang="scss" scoped>
.mill-detail {
  .panel-top,
  .panel-bottom {
    .item {
      background-color: #ffffff;
      box-shadow: 0 0 5 0 rgba(0, 0, 0, 0.05);
      border-radius: 3px;
      border: solid 1px #e0e0e0;
      overflow: hidden;
      .item-title {
        height: 50px;
        padding: 13px 20px;
        background-color: #f9f9f9;
        box-shadow: inset 0px -1px 0px 0px #f2f2f2;
        font-size: 12px;
        line-height: 24px;
        .name {
          color: #333333;
        }
        .button-box {
          display: flex;
          width: 110px;
          height: 24px;
          background-color: #ffffff;
          border-radius: 4px;
          border: solid 1px #cccccc;
          overflow: hidden;
          button {
            border: none;
            outline: none;
            flex: 1;
            border-right: 1px solid #cccccc;
            background-color: #f4f4f4;
            color: #646464;
            &:last-of-type {
              border-right: none;
            }
            &.active {
              background-color: #fff;
            }
            &:disabled {
              cursor: not-allowed;
            }
          }
        }
      }
    }
  }
  .panel-top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30px;
    .item-content {
      height: 120px;
      display: flex;
      line-height: 36px;
      padding-top: 24px;
      .conetnt-item {
        text-align: center;
        overflow: hidden;
        .item-top {
          color: #333333;
          margin-bottom: 10px;
          height: 36px;
          .value {
            font-size: 22px;
          }
          .unit {
            font-size: 14px;
          }
        }
        .item-bottom {
          .title {
            font-size: 18px;
            color: #cccccc;
          }
        }
      }
    }
    .item:nth-of-type(1) {
      width: 300px;
      .item-content {
        padding-left: 10px;
        padding-right: 10px;
        .conetnt-item {
          flex: 1;
        }
      }
    }
    .item:nth-of-type(2) {
      width: 330px;
      .item-content {
        padding-left: 12px;
        padding-right: 12px;
        .conetnt-item {
          padding: 0 12px;
          &:nth-of-type(1) {
            width: 100px;
          }
          &:nth-of-type(2) {
            flex: 1;
          }
        }
      }
    }
    .item:nth-of-type(3) {
      width: 470px;
      .item-content {
        padding-left: 10px;
        padding-right: 10px;
        .conetnt-item {
          padding: 0 10px;
          &:nth-of-type(1) {
            width: 250px;
          }
          &:nth-of-type(2) {
            flex: 1;
          }
        }
      }
    }
  }
  .panel-bottom {
    .item {
      .item-content {
        height: 465px;
      }
    }
  }
}
</style>

